#include <Arduino.h>
#include <Wire.h>
#include <WiFi.h>

// WiFi配置
const char* ssid = "mhf_mi";
const char* password = "mhf123321";

// 时间配置
#define UTC_OFFSET 8      // 北京时间UTC+8
#define NTP_SERVER "ntp1.aliyun.com"  // 阿里云NTP服务器

// 前向声明
void scanI2CDevices();
void checkCommonIssues();
void printBeijingTime();

// I2C配置
#define I2C_SDA 21
#define I2C_SCL 22
#define I2C_FREQ 100000

void setup() {
  Serial.begin(115200);
  Wire.begin(I2C_SDA, I2C_SCL, I2C_FREQ);
  
  // 连接WiFi
  WiFi.begin(ssid, password);
  Serial.print("Connecting to WiFi");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("\nConnected!");
  
  // 配置时区
  configTime(UTC_OFFSET * 3600, 0, NTP_SERVER);
  printBeijingTime();
  Serial.println("Starting I2C Scanner...");
}

void loop() {
  scanI2CDevices();
  delay(5000);
}

void printBeijingTime() {
  struct tm timeinfo;
  if(!getLocalTime(&timeinfo)){
    Serial.print("[Time Sync Failed] ");
    return;
  }
  
  Serial.printf("[%04d-%02d-%02d %02d:%02d:%02d] ",
               timeinfo.tm_year + 1900,
               timeinfo.tm_mon + 1,
               timeinfo.tm_mday,
               timeinfo.tm_hour,
               timeinfo.tm_min,
               timeinfo.tm_sec);
}

void scanI2CDevices() {
  int foundCount = 0;
  uint8_t error;

  printBeijingTime();
  Serial.println("Scanning I2C bus...");
  
  for (uint8_t address = 0x08; address < 0x78; address++) {
    Wire.beginTransmission(address);
    error = Wire.endTransmission();

    if (error == 0) {
      printBeijingTime();
      Serial.printf("Found device at 0x%02X", address);
      if (address == 0x40) {
        Serial.print(" (PCA9685 DEFAULT)");
      } else if (address >= 0x40 && address <= 0x7F) {
        Serial.print(" (Possible PCA9685)");
      }
      Serial.println();
      foundCount++;
    }
  }

  if (foundCount == 0) {
    checkCommonIssues();
  }
}

void checkCommonIssues() {
  printBeijingTime();
  Serial.println("Troubleshooting Tips:");
  printBeijingTime();
  Serial.println("1. Check I2C connections (SDA/SCL)");
  printBeijingTime();
  Serial.println("2. Verify PCA9685 power supply (5V)");
  printBeijingTime();
  Serial.println("3. Confirm address pins configuration");
}